/*
 *	dfclient.c
 *	© 2009 DigiFi Limited
 *
 *	The core of libdigifi and dfclient
 *
 */

#include "../headers/dfclient.h"


// connect callbacks
static void df_rget_callback(int err);

// the callback pointer for connect/disconnect
static void (*callback_ptr)(int);



int df_connect(char *ipaddress, int num_threads, void (*callback)(int)) {
	int err;

	callback_ptr = callback;

	// init the regex functions
	if ((err = dfregex_init()) < 0) return err;	

	// start up the threads
	if ((err = dfmultithread_init(ipaddress, num_threads)) < 0 ) return err;
	
	// setup the rget thread
	if ((err = dfrget_init(df_rget_callback)) < 0) return err;
	
	return 0;
}

static void df_rget_callback(int err) {
	// call register rgets
	dfrget_enable();
	
	// as this is the end of the chain callback on callback_ptr
	if (callback_ptr != NULL) { callback_ptr(0); callback_ptr == NULL; }
}


int df_connected(void) {
	return dfmultithread_connected() && dfrget_connected();
}



void df_disconnect(void) {	
	// shutdown the rgets
	dfrget_shutdown();
	
	// shutdown the threads
	dfmultithread_shutdown();
}

int df_queuecommand(unsigned int type, char *regex_name, void (*callback)(void), char *command, ...) {
	char *buffer;
	va_list arg_ptr;
	int err;
	
	va_start(arg_ptr, command);
	vasprintf(&buffer, command, arg_ptr);
	va_end(arg_ptr);
	
	err = dfmultithread_queue(type, regex_name, callback, buffer);
	
	return err;
}
